﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using GoodMan.Infrastructure.Entities.Enum;
using GoodMan.Portal.WebLogic;
using GoodMan.Infrastructure.Entities.Entity;
using GoodMan.Portal.Biz;
using GoodMan.Portal.Web.Models;
using GoodMan.Tool.Framework;
using GoodMan.Infrastructure.Entities;


namespace GoodMan.Portal.Web.Controllers
{
    [Warp]
    [ErrorHandle]
    [Compress]
    [Auth(UserRole.Member)]
    public class UserCenterController : Controller
    {
        public ActionResult Index()
        {
            ViewBag.User = new User().Find(HttpContext.User.Identity.Name);
            ViewBag.Integration = new Integration().Find(HttpContext.User.Identity.Name);
            ViewBag.AllOrderPrice = OrderBiz.GetAllOrderPriceSum(HttpContext.User.Identity.Name);
            ViewBag.Order = OrderBiz.GetNewOrders(HttpContext.User.Identity.Name, 0, 5);
            return View();
        }

        public ActionResult info()
        {
            ViewBag.FloorList = iCache.Get("SupportBiz.GetDormitories", () => SupportBiz.GetDormitories(), 6000);
            ViewBag.User = new User().Find(HttpContext.User.Identity.Name);
            return View();
        }

        [HttpPost]
        public ActionResult info(RegisterModel model)
        {
            ViewBag.FloorList = iCache.Get("SupportBiz.GetDormitories", () => SupportBiz.GetDormitories(), 6000);
            var user = new User().Find(HttpContext.User.Identity.Name);
            if (user != null)
            {
                user.NickName = model.NickName;
                user.RealName = model.RealName;
                user.Gender = (Gender) model.Gender;
                user.Birthday = model.Birthday;
                user.QQ = model.QQ;
                user.Phone = model.Phone;
                user.Dormitory = model.Dormitory;
                user.FloorId = model.FloorId;
                user.IdCardNo = model.IdCardNo;
                if (!String.IsNullOrEmpty(model.Photo))
                {  
                    user.Photo = model.Photo;
                }
                if (user.PostModify() != null)
                {
                    ViewBag.User = new User().Find(HttpContext.User.Identity.Name);
                    ViewBag.Success = "修改成功";
                    return View();
                }
            }
            ViewBag.User = new User().Find(HttpContext.User.Identity.Name);
            ViewBag.Success = "修改失败，请稍后重试";
            return View();
        }

        public ActionResult mypwd()
        {
            return View();
        }
        [HttpPost]
        public ActionResult mypwd(string oldpwd, string password)
        {
            var user = new User().Find(HttpContext.User.Identity.Name);
            if (user != null)
            {
                if (user.Password == AesAlgorithm.Encrypt(oldpwd))
                {
                    user.Password = AesAlgorithm.Encrypt(password);
                    user.PostModify();
                    ViewBag.Success = "修改成功";
                }
                else
                {
                    ViewBag.Success = "修改失败，原密码错误";
                }
            }
            else
            {
                ViewBag.Success = "用户不存在";
            }
            return View();
        }

        public ActionResult refund()
        {
            ViewBag.Integration = new Integration().Find(HttpContext.User.Identity.Name);
            return View();
        }
        [HttpPost]
        public ActionResult refund(decimal refund, string password)
        {
            int code = SupportBiz.Refund(HttpContext.User.Identity.Name, refund, password);
            if (code == 0)
            {
                return RedirectToAction("refundResult");
            }
            if(code == -1)
            {
                //余额不足
                return RedirectToAction("refundResult", new { code = 1 });
            }
            return RedirectToAction("refundResult", new { code=2});
        }
        public ActionResult refundResult(int code = 0)
        {
            ViewBag.Code = code;
            return View();
        }
        public ActionResult order(int page=0)
        {
            ViewBag.Orders = new ItemListBox<Order>(OrderBiz.GetNewOrders(HttpContext.User.Identity.Name, page, 10))
                .BuildPage(new Order().Count(c => c.UserName == HttpContext.User.Identity.Name), page, 10, new PageParameter() { Style = "home" });
            return View();
        }
        public void SWFPrepareUpload()
        {
            new UploadTool().SWFPrepareUpload("/content/file/head/");
        }

        #region 订单详情
        public ActionResult OrderDetail(int id)
        {
            Order order = new Order().Find(id.ToString());
            List<OrderDetail> orderDetailList = new OrderDetail().FindAll(c => c.OrderId == id);
            string name = System.Web.HttpContext.Current.User.Identity.Name;
            var user = new User().Find(name);
            ViewBag.User = user;
            ViewBag.Order = order;
            ViewBag.OrderDetail = orderDetailList;
            ViewBag.OrderHistory = new OrderHistory().FindAll(c => c.OrderId == order.Id);
            return View();
        }

        
        #endregion

        public ActionResult ProductAppraisie(int id)
        {
            var products = ProductBiz.ProductAppraisie(id);
             
            ViewBag.products = products;
            ViewBag.OrderId = id;
            return View();
        }

        public ActionResult DoAppraisie(string pids,int orderId)
        {
            if (pids != null && pids.Length > 1)
            {
                foreach (var pid in pids.Substring(0, pids.Length - 1).Split(','))
                {
                    string appraiseContent = Request.Form["appraiseContent" + pid].ToString();
                    int appraiseGrade =int.Parse(Request.Form["appraiseGrade" + pid].ToString());
                    
                    string username = System.Web.HttpContext.Current.User.Identity.Name;
                    var appraise = new Appraise()
                    {
                        OrderId=orderId,
                        AppraiseContent = appraiseContent,
                        AppraiseDate = DateTime.Now,
                        AppraiseGrade = appraiseGrade,
                        ProductId = int.Parse(pid),
                        UserName = username,
                        State = 1
                    };
                    AppraiseBiz.SaveAppraise(appraise);
                    var product = new Product().Find(pid.ToString());
                    if (product.AreaCode==AreaCode.Snack)
                    {
                        //计算商家的评分  每一个等级哪一个最多商家评分就是那一个
                        var business = new Business().Find(product.BusinessId.ToString());
                        if (business != null)
                        {
                            business.Levels = AppraiseBiz.CalcBusinessAppraise(product.BusinessId);
                        }
                        business.PostModify();
                         
                    }
                }
            }
            return Redirect("/usercenter/order");
        }
    }
}